import * as XLSX from 'xlsx'
import { save } from '@tauri-apps/api/dialog'
import { writeTextFile } from '@tauri-apps/api/fs'
import type { ExportOptions } from '../types'

export async function exportData(options: ExportOptions) {
  try {
    const filePath = await save({
      filters: [{
        name: options.format === 'json' ? 'JSON Files' : 
              options.format === 'csv' ? 'CSV Files' : 'Excel Files',
        extensions: [options.format === 'excel' ? 'xlsx' : options.format]
      }],
      defaultPath: `${options.filename}.${options.format === 'excel' ? 'xlsx' : options.format}`
    })

    if (!filePath) return

    switch (options.format) {
      case 'json':
        await writeTextFile(filePath, JSON.stringify(options.data, null, 2))
        break
      case 'csv':
        const csv = convertToCSV(options.data)
        await writeTextFile(filePath, csv)
        break
      case 'excel':
        const ws = XLSX.utils.json_to_sheet(options.data)
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
        const excelData = new Uint8Array(excelBuffer)
        await writeBinaryFile(filePath, excelData)
        break
    }

    return true
  } catch (error) {
    console.error('导出失败:', error)
    throw error
  }
}

export async function importJSON(): Promise<any[]> {
  try {
    const filePath = await open({
      filters: [{
        name: 'JSON Files',
        extensions: ['json']
      }]
    })

    if (!filePath) return []

    const content = await readTextFile(filePath)
    return JSON.parse(content)
  } catch (error) {
    console.error('导入失败:', error)
    throw error
  }
}

function convertToCSV(data: any[]): string {
  if (!data || data.length === 0) return ''

  const headers = Object.keys(data[0])
  const csvHeaders = headers.join(',')

  const csvRows = data.map(row => {
    return headers.map(header => {
      const value = row[header] ?? ''
      return typeof value === 'string' && value.includes(',') ? `"${value}"` : value
    }).join(',')
  })

  return [csvHeaders, ...csvRows].join('\n')
}

// 辅助函数
import { writeBinaryFile } from '@tauri-apps/api/fs'
import { open, readTextFile } from '@tauri-apps/api/fs'
